package com.biu.billiards.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biu.billiards.mapper.ShopMapper;
import com.biu.billiards.model.bo.OrderAdminBO;
import com.biu.billiards.mapper.OrderMapper;
import com.biu.billiards.model.bo.SumBO;
import com.biu.billiards.model.bo.SumShopBO;
import com.biu.billiards.model.bo.WaterBo;
import com.biu.billiards.model.entity.OrderAdmin;
import com.biu.billiards.model.entity.Shop;
import com.biu.billiards.model.vo.mqtt.OpenBilliardsVo;
import com.biu.billiards.model.vo.shop.orderAdmin.AddOrderAdminVo;
import com.biu.billiards.model.vo.shop.orderAdmin.GetOrderAdminVo;
import com.biu.billiards.model.vo.shop.orderAdmin.UpdateOrderAdminVO;
import com.biu.billiards.model.vo.shop.GetShopVo;
import com.biu.billiards.model.vo.user.GetUserVo;
import com.biu.billiards.service.IBilliardsService;
import com.biu.billiards.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biu.billiards.service.IShopService;
import com.biu.billiards.service.IUserService;
import com.biu.billiards.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue
 * @since 2023-09-25
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderAdmin> implements IOrderService {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private IBilliardsService billiardsService;

    @Resource
    private IUserService userService;

    @Resource
    private ShopMapper shopMapper;


    @Resource
    private RedisUtils redisUtils;

    @Override
    public List<SumShopBO> allListShopSum(GetShopVo getShopVo) {


        QueryWrapper<Shop> queryWrapper2 = new QueryWrapper<>();

        List<Shop> sumShopList = shopMapper.selectList(queryWrapper2);

        List<SumShopBO> sum = new ArrayList<>();

        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDateTime = LocalDate.parse(getShopVo.getStartTime(), formatter);
        LocalDate endDateTime = LocalDate.parse(getShopVo.getEndTime(), formatter);
        queryWrapper.between("create_time", getShopVo.getStartTime(), endDateTime.plusDays(1).toString());



        List<OrderAdmin> orderAdminList = orderMapper.selectList(queryWrapper);

        long daysBetween = ChronoUnit.DAYS.between(startDateTime, endDateTime);


        for (Shop shop:sumShopList){

            for (int i = 0; i <= daysBetween; i++) {

                SumShopBO sumBO = new SumShopBO();
                BigDecimal shop_actual_sum = new BigDecimal(0);

                for (OrderAdmin orderAdmin:orderAdminList){


                    if (orderAdmin.getCreateTime().getDayOfMonth() == startDateTime.plusDays(i).getDayOfMonth() && orderAdmin.getShopId()!=null &&   orderAdmin.getShopId().equals(shop.getShopId())){
                        if (orderAdmin.getShopActualSum()!=null){
                            shop_actual_sum=shop_actual_sum.add(orderAdmin.getShopActualSum());
                        }
                    }
                }
                sumBO.setShop_actual_sum(shop_actual_sum);
                sumBO.setShopId(shop.getShopId());
                sum.add(sumBO);
            }


        }




        return sum;
    }

    @Override
    public List<SumBO> allListSum(GetShopVo getShopVo) {


        List<SumBO> sum = new ArrayList<>();


        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDateTime = LocalDate.parse(getShopVo.getStartTime(), formatter);
        LocalDate endDateTime = LocalDate.parse(getShopVo.getEndTime(), formatter);
        queryWrapper.between("create_time", getShopVo.getStartTime(), endDateTime.plusDays(1).toString());


        System.out.println("getShopV213123123o");
        System.out.println(getShopVo);

        List<OrderAdmin> orderAdminList = orderMapper.selectList(queryWrapper);
        System.out.println("dsdfdsfdsfds");
        System.out.println(orderAdminList.size());





        long daysBetween = ChronoUnit.DAYS.between(startDateTime, endDateTime);


        for (int i = 0; i <= daysBetween; i++) {

            SumBO sumBO = new SumBO();
            BigDecimal shop_actual_sum = new BigDecimal(0);
            BigDecimal recommend_actual_sum = new BigDecimal(0);
            BigDecimal platform_actual_sum = new BigDecimal(0);


            for (OrderAdmin orderAdmin:orderAdminList){

                if (orderAdmin.getCreateTime().getDayOfMonth() == startDateTime.plusDays(i).getDayOfMonth()){

                    if (orderAdmin.getShopActualSum()!=null){
                        shop_actual_sum=shop_actual_sum.add(orderAdmin.getShopActualSum());
                    }
                    if (orderAdmin.getRecommendActualSum()!=null){
                        recommend_actual_sum=recommend_actual_sum.add(orderAdmin.getRecommendActualSum());
                    }

                    if (orderAdmin.getPlatformActualSum()!=null){
                        platform_actual_sum=platform_actual_sum.add(orderAdmin.getPlatformActualSum());
                    }


                }
            }


            sumBO.setPlatform_actual_sum(platform_actual_sum);
            sumBO.setRecommend_actual_sum(recommend_actual_sum);
            sumBO.setShop_actual_sum(shop_actual_sum);

            sum.add(sumBO);

        }


//        for (OrderAdmin orderAdmin:orderAdminList){
//
//
//            SumBO sumBO = new SumBO();
//
//            if (orderAdmin.getShopActualSum()!=null){
//                shop_actual_sum=shop_actual_sum.add(orderAdmin.getShopActualSum());
//            }
//            if (orderAdmin.getRecommendActualSum()!=null){
//                recommend_actual_sum=recommend_actual_sum.add(orderAdmin.getRecommendActualSum());
//            }
//
//            if (orderAdmin.getPlatformActualSum()!=null){
//                platform_actual_sum=platform_actual_sum.add(orderAdmin.getPlatformActualSum());
//            }
//            sumBO.setShop_actual_sum(shop_actual_sum);
//            sumBO.setRecommend_actual_sum(recommend_actual_sum);
//            sumBO.setPlatform_actual_sum(platform_actual_sum);
//            sum.add(sumBO);
//
//
//        }


        return sum;
    }

    @Override
    public SumBO allSum() {



        SumBO sumBO = new SumBO();

        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
//        LambdaQueryWrapper<OrderAdmin> lambdaWrapper = queryWrapper.lambda();
//// 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//// 设置查询条件，查询最近7天的数据
//        lambdaWrapper.ge(OrderAdmin::getCreateTime, currentDate.minusDays(7))
//                .le(OrderAdmin::getCreateTime, currentDate);
        List<OrderAdmin> orderAdminList = orderMapper.selectList(queryWrapper);


        BigDecimal shop_actual_sum = new BigDecimal(0);
        BigDecimal recommend_actual_sum = new BigDecimal(0);
        BigDecimal platform_actual_sum = new BigDecimal(0);

        for (OrderAdmin orderAdmin:orderAdminList){


            if (orderAdmin.getShopActualSum()!=null){
                shop_actual_sum=shop_actual_sum.add(orderAdmin.getShopActualSum());
            }
            if (orderAdmin.getRecommendActualSum()!=null){
                recommend_actual_sum=recommend_actual_sum.add(orderAdmin.getRecommendActualSum());
            }

            if (orderAdmin.getPlatformActualSum()!=null){
                platform_actual_sum=platform_actual_sum.add(orderAdmin.getPlatformActualSum());
            }


        }

        sumBO.setShop_actual_sum(shop_actual_sum);
        sumBO.setRecommend_actual_sum(recommend_actual_sum);
        sumBO.setPlatform_actual_sum(platform_actual_sum);
        System.out.println("SumBOadasd");
        System.out.println(sumBO);

        return sumBO;
    }



    @Override
    public List<WaterBo> getPieInfo(GetShopVo getShopVo) {

        System.out.println("getShopVo");
        System.out.println(getShopVo);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDateTime = LocalDate.parse(getShopVo.getStartTime(), formatter);
        LocalDate endDateTime = LocalDate.parse(getShopVo.getEndTime(), formatter);

        List<WaterBo> waterBoList = new ArrayList<>();
        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", getShopVo.getShopId());
        queryWrapper.eq("order_status", 1);
        queryWrapper.between("create_time", getShopVo.getStartTime(), endDateTime.plusDays(1).toString());


        List<OrderAdmin> orderAdminList = orderMapper.selectList(queryWrapper);


        System.out.println("orderAdminList");
        System.out.println(orderAdminList);



        for (int i = 0; i < 4; i++) {
            WaterBo waterBo = new WaterBo();
            BigDecimal initPrice0 = new BigDecimal(0);
            BigDecimal initPrice1 = new BigDecimal(0);
            BigDecimal initPrice2 = new BigDecimal(0);
            BigDecimal initPrice3 = new BigDecimal(0);



            if (i==0){

                waterBo.setName("微信");
                waterBo.setValue(initPrice0);

            }else if (i==1){
                waterBo.setName("抖音");
                waterBo.setValue(initPrice1);
            }else if (i==2){
                waterBo.setName("余额");
                waterBo.setValue(initPrice2);
            }else {
                waterBo.setName("美团");
                waterBo.setValue(initPrice3);
            }


            for (OrderAdmin orderAdmin:orderAdminList){

                if (orderAdmin.getPlayWay().equals("微信支付") && i==0){

                    waterBo.setName("微信");
                    initPrice0=initPrice0.add(orderAdmin.getActualPrice());
                    waterBo.setValue(initPrice0);

                }else if (orderAdmin.getPlayWay().equals("抖音核销") && i==1){
                    waterBo.setName("抖音");
                    initPrice1=initPrice1.add(orderAdmin.getActualPrice());
                    waterBo.setValue(initPrice1);

                }else if (orderAdmin.getPlayWay().equals("余额支付") && i==2){
                    waterBo.setName("余额");
                    initPrice2=initPrice2.add(orderAdmin.getActualPrice());
                    waterBo.setValue(initPrice2);

                }else if (orderAdmin.getPlayWay().equals("美团核销") && i==3){
                    waterBo.setName("美团");
                    initPrice3=initPrice3.add(orderAdmin.getActualPrice());
                    waterBo.setValue(initPrice3);

                }



            }

            waterBoList.add(waterBo);

        }






        return waterBoList;
    }

    // 9754 4772 80
    @Override
    public List<WaterBo> getStreamInfo(GetShopVo getShopVo) {


        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDateTime = LocalDate.parse(getShopVo.getStartTime(), formatter);
        LocalDate endDateTime = LocalDate.parse(getShopVo.getEndTime(), formatter);

        System.out.println("startDateTime3324234234234");
        System.out.println(startDateTime);
        System.out.println(endDateTime);

        List<WaterBo> waterBoList = new ArrayList<>();
        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", getShopVo.getShopId());
        queryWrapper.eq("order_status", 1);

        queryWrapper.between("create_time", getShopVo.getStartTime(), endDateTime.plusDays(1).toString());




        List<OrderAdmin> orderAdminList = orderMapper.selectList(queryWrapper);

        System.out.println("orderAdminList");
        System.out.println(orderAdminList);
        System.out.println("getShopVo");
        System.out.println(getShopVo);

        long daysBetween = ChronoUnit.DAYS.between(startDateTime, endDateTime);



         for (int i = 0; i <= daysBetween; i++) {
             WaterBo waterBo = new WaterBo();
             BigDecimal initPrice = new BigDecimal(0);
             waterBo.setName(startDateTime.plusDays(i).toString());
             waterBo.setValue(initPrice);

             for (OrderAdmin orderAdmin:orderAdminList){

//                 System.out.println("etDayOfMonth()");
//                 System.out.println(orderAdmin.getCreateTime());
//                 System.out.println(orderAdmin.getCreateTime().getDayOfMonth());
//                 System.out.println(startDateTime.getDayOfMonth());
//                 System.out.println(startDateTime.getDayOfMonth()+i);

                // startDateTime.getDayOfMonth()+i


                if (orderAdmin.getCreateTime().getDayOfMonth() == startDateTime.plusDays(i).getDayOfMonth()){


                    initPrice=initPrice.add(orderAdmin.getActualPrice());
                    waterBo.setValue(initPrice);

                }
             }

             waterBoList.add(waterBo);

         }





        return waterBoList;
    }





    @Override
    public IPage<OrderAdminBO> getOrderPage(GetOrderAdminVo getOrderVo) {
        QueryWrapper<OrderAdmin> query = new QueryWrapper<>();


        if (getOrderVo.getUserId()!=null){
            query.eq("user_id",getOrderVo.getUserId());
        }

        if (getOrderVo.getPhone()!=null){
            query.like("phone",getOrderVo.getPhone());
        }

        if (getOrderVo.getShopId()!=null){
            query.eq("shop_id",getOrderVo.getShopId());
        }


        if (getOrderVo.getOrderType()!=0){
            query.eq("order_type",getOrderVo.getOrderType());
        }

        if (getOrderVo.getOrderStatus()!=2){
            query.eq("order_status",getOrderVo.getOrderStatus());
        }

        if (getOrderVo.getDivideType()!=null && getOrderVo.getDivideType()==1){
            query.eq("play_way","微信支付").or().eq("play_way","余额支付");
        }


        query.orderByDesc("create_time");

        //新建分页条件
        Page<OrderAdmin> p = new Page<>(getOrderVo.getCurrentPage(),getOrderVo.getPageSize());
        IPage<OrderAdmin> userIPage = orderMapper.selectPage(p,query);
        IPage<OrderAdminBO> page = new Page<>();
        List<OrderAdminBO> adminDetailBOList = new ArrayList<>();
        for (OrderAdmin admin: userIPage.getRecords()){
            OrderAdminBO adminDetailBO = new OrderAdminBO();
            BeanUtils.copyProperties(admin,adminDetailBO);
            adminDetailBOList.add(adminDetailBO);
        }
        /* 将转化的BO放到的Records里面  */
        page.setRecords(adminDetailBOList);
        page.setCurrent(userIPage.getCurrent());
        page.setPages(userIPage.getPages());
        page.setPages(userIPage.getSize());
        page.setTotal(userIPage.getTotal());

        return page;
    }

    @Override
    public Boolean recommendOrder(AddOrderAdminVo addOrderAdminVo) {



        return null;
    }

    @Override
    public Boolean orderNumber() {

        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", 1);


        Integer nowNumber= orderMapper.selectCount(queryWrapper);

        String oldNumber = redisUtils.get("orderNumber");

        if (oldNumber!=null){

            if (nowNumber!=Integer.parseInt(oldNumber)){
                redisUtils.set("orderNumber",nowNumber.toString());

                return  true;
            }
        }else {

            redisUtils.set("orderNumber",nowNumber.toString());

        }


        return  false;
    }


    @Override
    public Boolean topUpOrder(AddOrderAdminVo addOrderAdminVo) {

        OrderAdmin order = new OrderAdmin();

        order.setOrderId("sadaaaa");

        //order.setOrderStatus()
       BeanUtils.copyProperties(addOrderAdminVo,order);
        System.out.println("order");
        System.out.println(order);
        return orderMapper.insert(order) == 1;
    }

    @Override
    public Boolean updateOrder(UpdateOrderAdminVO updateOrderVO) {
        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",updateOrderVO.getOrderId());
        OrderAdmin order = orderMapper.selectOne(queryWrapper);

        return orderMapper.update(order, queryWrapper) == 1;
    }

    @Override
    public Boolean updateOrderStatus(String out) {

        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",out);
        OrderAdmin order = orderMapper.selectOne(queryWrapper);

        order.setOrderStatus(1);
        order.setStartTime(LocalDateTime.now());
        order.setEndTime(LocalDateTime.now().plusHours(order.getBilliardsHour()));

        OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();

        openBilliardsVo.setBilliardsNumber(order.getBilliardsNumber());
        openBilliardsVo.setDeviceNumber(order.getDeviceNumber());

        openBilliardsVo.setBilliardsId(order.getBilliardsId());
        openBilliardsVo.setHour(order.getBilliardsHour());
        openBilliardsVo.setOpen(1);
        openBilliardsVo.setHardwareId(order.getHardwareId());
       // openBilliardsVo.setGoodsType(0);

        openBilliardsVo.setShopId(order.getShopId());
        billiardsService.openBilliards(openBilliardsVo);


        return orderMapper.update(order, queryWrapper) == 1;
    }

    @Override
    public Boolean updateOrderPayStatus(String out) {

        System.out.println("进来啊啊啊");
        System.out.println(out);

        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",out);
        OrderAdmin order = orderMapper.selectOne(queryWrapper);

        order.setOrderStatus(1);
        order.setCreateTime(LocalDateTime.now());

        GetUserVo getUserVo = new GetUserVo();
        getUserVo.setUserId(order.getUserId());
        getUserVo.setPayPrice(order.getPayPrice());

        userService.userTopUp(getUserVo);


        return orderMapper.update(order, queryWrapper) == 1;
    }

    @Override
    public Boolean addOrder(AddOrderAdminVo addOrderVo) {
        OrderAdmin order = new OrderAdmin();
        BeanUtils.copyProperties(addOrderVo,order);
        System.out.println("order");
        System.out.println(order);









        return orderMapper.insert(order) == 1;
    }


    @Override
    public Boolean deleteOrder(String orderId) {
        QueryWrapper<OrderAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        return orderMapper.delete(queryWrapper) == 1;
    }
}
